package demo1;


import java.util.Arrays;
import java.util.Comparator;

//接口的应用！
// 比较两个对象的尝试！
// 实现关于comparable接口！
class Student implements Comparable<Student> {
    String name;
    int age;

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    //要比较接口中的对象
//本质上依然是比较一个属性

    public int compareTo(Student o) {
        //比较年龄：

        if(this.age == o.age){
            return 0;
        }else if(this.age>o.age){
            return 1;
        }else {
            return -1;
        }
    }
        //比较姓名
      //  return this.name.compareTo(o.name);
    }
    public class Test {
        //尝试实现自己的sort
    public  static     void mysort(Comparable[] comparables){
        // 用接口数组接收实现接口的数组   采用冒号排序的方式
        //比较的趟数！
        for (int i = 0;i<comparables.length-1 ;i++){
              for (int j = 0; j<comparables.length - 1-i;j++){
                  if(comparables[j].compareTo(comparables[j+1])>0){
                       //如果数组前面元素的值大于数组后面元素的值，则交换引用的值,这是升序
                      Comparable tmp  = comparables[j];
                      comparables[j]  = comparables[j+1];
                      comparables[j+1] = tmp;
                  }
              }

        }
    }
        public static void main(String[] args) {

           /* Student student1 = new Student(10,"张三");
            Student student2 = new Student(12,"李四");
            //System.out.println(student1>student2);
            System.out.println(student1.compareTo(student2));*/

            int age1 = 10;
            int age2 = 8;
            //      System.out.println(age1 == age2);
            Student[] arr1 = new Student[3];


            arr1[0] = new Student(10, "王五");
            arr1[1] = new Student(8, "李四");
            arr1[2] = new Student(9, "张三");
            //     Student[] arr1 = {student1,student2,student3};
            System.out.println("排序前：" + Arrays.toString(arr1));
       //     NameComparator nameComparator   =  new NameComparator();
     //       Arrays.sort(arr1,nameComparator);
         //   Arrays.sort(arr1);
             // mysort(arr1);
     //       System.out.println("排序后：" + Arrays.toString(arr1));
            //此时比较的是引用中的地址！
            //      System.out.println(student1.compareTo(student2));


// 上面的代码中，只能固定地比较对象中一种属性，我们怎样解决这个问题，就是换一种接口
//针对不同的属性，换不同的接口！
            //根据名字进行比较
       //     NameComparator nameComparator   =  new NameComparator();
       //     Arrays.sort(arr1,nameComparator);
         //   System.out.println("排序后："+Arrays.toString(arr1));
            //根据年龄进行比较
            AgeComparator ageComparator = new AgeComparator();
            //根据年龄进行比较！
            Arrays.sort(arr1,ageComparator);
            System.out.println("排序后："+Arrays.toString(arr1));

        }
    }
